define(function(require, exports, module) {
	'use strict';
    
    var rk = require('rk')

    $.widget('rk.rotate', {
        _map: {
            login: 0,
            regist: 1,
            forgot: 2
        },
        _create: function() {
            var $this = this;
            this.panels = this.element.find('>div.main');
            this.element.on('click.' + this.widgetName, '[switchto]', function(evt) {
                evt.target.nodeName == 'A' && evt.preventDefault();
                $this.show($(this).attr('switchto'));
            });
        },
        show: function(name, oLoger) {
            this.panels.hide();
            var panel = this.panels.eq(this._map[name])
            panel[name](oLoger);
            panel.show('fade');
            this._delay(function() {
                panel.find('input:visible:first').focus();
            });
        }
    });

    $.widget('rk.login', {
        options: {
            cookieName: '',
            loginName: ''
        },
        _create: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            this.panels = this.element.find('>div.main');
            this.element.on('click.' + this.widgetName, '[switchto]', function(evt) {
                evt.target.nodeName == 'A' && evt.preventDefault();
                $this.show($(this).attr('switchto'));
            });
            this.element.find('a.ios_download').on('click.' + this.widgetName, function(evt) {
                evt.preventDefault();
                $this.iosDownload();
            });

            this.element.find('a.android_download').on('click.' + this.widgetName, function(evt) {
                evt.preventDefault();
                $this.androidDownload();
            });


            $this.$passport = $elem.find('input[name="loginName"]');
            $this.$password = $elem.find('input[name="password"]');
            $this.$error = $elem.find('label.error_info');
            $this.$verify = $elem.find('ul.verification_form');
            $this.$iptCode = $this.$verify.find('input.input_code');
            $this.$sessionId = $this.$verify.find('input.input_sessionId');
            $this.$change = $this.$verify.find('a.change');
            $this.$img = $this.$verify.find('img.img_code');
            $this.$submit = $elem.find('a.button_blue').first();
            $this.$submiting = $elem.find('a.button_waiting');
            $this.$form = $elem.find('form');


            $(document).on('keyup', function(evt) {
                evt.keyCode == 13 && $this.submit();
            });

            $this.$passport.on('blur', function(evt) {
                $this.checkPassport() && $this.validatePassport();
            });

            $this.$change.on('click', function(evt) {
                evt.preventDefault();
                $this.changeCode(evt);
            });

            $this.$submit.on('click', function(evt) {
                evt.preventDefault();
                $this.submit();
            });

            var loginName = opt.loginName || opt.cookieName || '';
            if (loginName) {
                $this.$passport.val(loginName).triggerHandler('blur');
            }
        },
        _init: function() {
            this.element.find('input').val('');
        },



        _mobileDownload: function(config) {
            showPic(config.src, function() {
                var tmpl = '<div class="pop_content clear"><ul class="pop_list"><li><h5>'+rk.i18n('LOGIN_DOWNLOAD_QR_CODE')+'</h5></li><li><img style="margin-left:80px;"/></li><li><a target="_blank" class="app_download">'+rk.i18n('LOGIN_OR_DOWNLOAD')+'</a></li></ul></div>';
                var $dialog = $(tmpl);
                $dialog.find('img').attr('src', config.src);
                $dialog.find('a.app_download').attr('href', config.url);
                $dialog.dialog({
                    width: 550,
                    title: config.title,
                    close: function() {
                        $(this).dialog('destroy');
                    }
                })
            });
        },
        iosDownload: function() {
            this._mobileDownload({
                src: SESSION.resDomain + '/img/ingagecrm_iphone.png',
                url: 'https://itunes.apple.com/cn/app/ingage-crm/id654720925?ls=1&mt=8',
                title: rk.i18n('LOGIN_IOS_DOWNLOAD')//'iOS客户端下载'
            });
        },
        androidDownload: function() {
            this._mobileDownload({
                src: SESSION.resDomain + '/img/ingagecrm_android.jpg',
                url: 'http://m.xiaoshouyi.com/apps/android',
                title: rk.i18n('LOGIN_ADROID_DOWNLOAD')//'安卓客户端下载'
            });
        },
        submit: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if (!$this.checkPassport() || !$this.checkPassword() || $this.$verify.is(':visible') && !$this.checkVerifyCode()) {
                return;
            }
            $this.loginStart();
            $this.ppCache = {};
            $.post($this.$form.attr('action'), $this.$form.serialize(), null, 'json').done(function(json) {
                $this.loginEnd();
                switch (json.status) {
                    case 400:
                    case 401:
                        $this.errorMsg(rk.i18n('LOGIN_PASSWORD_NOT_MATCH'));
                        if (json.data.needCode) {
                            $this.openVerify(json.data.sessionID);
                        } else {
                            $this.closeVerify();
                        }
                        break;
                    case 410:
                        $this.errorMsg(rk.i18n('LOGIN_BAD_CODE'));

                        break;
                    case 201:
                    case 202:
                        var $login = $("#loginDiv").html(json.data.view),
                            $ulCompany = $login.find('ul.company_list'),
                            $lis = $ulCompany.find('li'),
                            $hidTenantId = $login.find('input[name="tenantId"]');

                        $lis.on('click', function(evt) {
                            var $li = $(this);
                            $li.addClass("hover").siblings().removeClass("hover");
                            $hidTenantId.val($li.attr('tenantid'));
                        }).first().trigger('click');

                        $(document).on('keydown', function(evt) {
                            var code = evt.keyCode;
                            if (code == 38 || code == 40) {
                                if ($lis.filter('.hover').size() == 0) {
                                    $lis.first().trigger('click');
                                }
                                var $li = $lis.filter('.hover').first();
                                $li = $li[code == 38 ? 'prev' : 'next']();
                                if ($li.size() == 0) {
                                    $li = $lis[code == 38 ? 'last' : 'first']();
                                }
                                $li.trigger('click');
                            }
                        }).on('keyup', function(event) {
                            if (event.keyCode == 13) {
                                $("#login_entry_button").trigger("click");
                            }
                        });

                        $("#login_entry_button").on('click', function(evt) {

                        });

                        break;
                    case 0:
                        location.href = pageContextPath + "/route/ing.action";
                        break;
                    default:
                        $this.errorMsg(json.statusText);
                        $this.loginEnd();
                }
            }).fail(function() {
                $this.loginEnd(1000);
                $this.errorMsg(rk.i18n('LOGIN_SYS_BUSY'));
            });

        },
        loginStart: function() {
            this.$submit.hide();
            this.$submiting.show();
        },
        loginEnd: function(delay) {
            this._delay(function() {
                this.$submit.show();
                this.$submiting.hide();
            }, delay || 0);
        },
        checkPassport: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var pp = $.trim($this.$passport.val());
            if (!pp) {
                return $this.errorMsg(rk.i18n('LOGIN_NEED_CELL_OR_EMAIL'));
            }
            if (!$this.rMobile.test(pp) && !$this.rEmail.test(pp)) {
                return $this.errorMsg(rk.i18n('LOGIN_NEED_CURRECT_INPUT'));
            }
            return $this.errorMsg() || true;
        },
        checkPassword: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var pw = $this.$password.val();
            if (!pw) {
                return $this.errorMsg(rk.i18n('LOGIN_NEED_PASSWORD'));
            }
            return $this.errorMsg() || true;
        },
        checkVerifyCode: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var vc = $this.$iptCode.val();
            if (vc.length != 4) {
                return $this.errorMsg(rk.i18n('LOGIN_NEED_CODE'));
            }
            return $this.errorMsg() || true;
        },
        validatePassport: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var pp = $.trim($this.$passport.val());
            if ($this.lastPassPort != pp) {
                $this.ppCache = {};
                $this.lastPassPort = pp;
            }
            if ($this.ppCache[pp]) {
                $this._validatePassport($this.ppCache[pp]);
            } else {
                $.post('/global/request-nick-check.action', {
                    loginName: pp
                }, function(json) {
                    if (json.status == 0) {
                        $this._validatePassport($this.ppCache[pp] = json.data);
                    } else {

                    }
                }, 'json');
            }
        },
        _validatePassport: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var needcode = data.needCode;
            if (needcode) {
                $this.$verify.is(':hidden') && $this.openVerify(data.sessionID);
            } else {
                $this.closeVerify();
            }
        },
        openVerify: function(sessionId) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if ($this.$sessionId.val() != sessionId) {
                $this.$sessionId.val($this.sessionId = sessionId);
            }
            $this.$verify.show();
            $this.changeCode();
        },
        closeVerify: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            $this.$sessionId.val('');
            $this.$iptCode.val('');
            $this.$verify.hide();
        },
        changeCode: function(evt) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            $this.$img.attr('src', '/global/check-code.action?sessionID=' + $this.sessionId + '&' + Math.random());
            $this.$iptCode.val('');
            evt && !evt.isTrigger && $this.$iptCode.focus();
        },
        errorMsg: function(msg) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if (msg) {
                $this.$error.text(msg);
                if ($this.$error.is(':visible')) {
                    $this.$error.fadeTo('fast', 0.3).fadeTo('fast', 1);
                } else {
                    $this.$error.show();
                }
            } else {
                $this.$error.is(':visible') && $this.$error.hide();
            }
        },
        ppCache: {

        },
        rMobile: /^1[3|4|5|7|8][\d]{9}$/,
        rEmail: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
    });

    // $.widget('rk.regist', {
    //     _create: function() {
    //         var $this = this;
    //         this.panels = this.element.find('>div.main');
    //         this.element.on('click.' + this.widgetName, '[switchto]', function(evt) {
    //             evt.target.nodeName == 'A' && evt.preventDefault();
    //             $this.show($(this).attr('switchto'));
    //         });

    //         this.panels.eq(0).login();
    //         this.panels.eq(1).regist();
    //         this.panels.eq(2).forgot();
    //     },
    //     _init: function() {
    //         this.element.find('input').val('');
    //     }
    // });

    // $.widget('rk.forgot', {
    //     _create: function() {
    //         var $this = this;
    //         this.panels = this.element.find('>div.main');
    //         this.element.on('click.' + this.widgetName, '[switchto]', function(evt) {
    //             evt.target.nodeName == 'A' && evt.preventDefault();
    //             $this.show($(this).attr('switchto'));
    //         });

    //         this.panels.eq(0).login();
    //         this.panels.eq(1).regist();
    //         this.panels.eq(2).forgot();
    //     },
    //     _init: function() {
    //         this.element.find('input').val('');
    //     },
    //     show: function(name) {
    //         this.panels.hide();
    //         var panel = this.panels.eq(this._map[name]).show('fade');
    //         this._delay(function() {
    //             panel.find('input:visible:first').focus();
    //         });
    //     }
    // });

    function showPic(src, callback) {
        var img = new Image();
        img.onload = callback;
        img.src = src;
    }

    return {
        init: function($left, $right, oLoger) {
            showPic(SESSION.resDomain + '/img/register/left_cover20141115.jpg', function() {
                $left.addClass('left_img').hide().show('fade');
            });

            $right.login();
        }
    }
});
